//
//  JLScrollView.m
//  JLPhotoBrowser
//
//  Created by liao on 15/12/24.
//  Copyright © 2015年 BangGu. All rights reserved.
//

#define JLKeyWindow [UIApplication sharedApplication].keyWindow
#define NavigationHeigth 64

#define bigScrollVIewTag 101

#import "JLPhotoBrowser.h"
#import "UIImageView+WebCache.h"
#import "JLPieProgressView.h"
#import <Photos/Photos.h>

@interface JLPhotoBrowser()<UIScrollViewDelegate>
/**
 *  底层滑动的scrollview
 */
@property (nonatomic,weak) UIScrollView *bigScrollView;

/**
 *  原始frame数组
 */
@property (nonatomic,strong) NSMutableArray *originRects;

@end

@implementation JLPhotoBrowser

-(NSMutableArray *)originRects{
    
    if (!_originRects) {
        _originRects = [NSMutableArray array];
    }
    
    return _originRects;
    
}

+ (instancetype)photoBrowser{
    
    return [[self alloc] init];
    
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        //0.创建黑色背景view
        [self setupBlackView];
        
        //1.创建bigScrollView
        [self setupBigScrollView];
        
    }
    return self;
}

#pragma mark 创建黑色背景
- (UIView *)blackView {
    if (!_blackView) {
        UIView *blackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        [self addSubview:blackView];
        _blackView = blackView;
    }
    return _blackView;
}
-(void)setupBlackView{
    self.blackView.backgroundColor = [UIColor colorWithRed:30 / 255.0 green:30 / 255.0 blue:30 / 255.0 alpha:1];
}

#pragma mark 创建背景bigScrollView
-(void)setupBigScrollView{
    
    UIScrollView *bigScrollView = [[UIScrollView alloc] init];
    bigScrollView.backgroundColor = [UIColor clearColor];
    bigScrollView.delegate = self;
    bigScrollView.tag = bigScrollVIewTag;
    bigScrollView.pagingEnabled = YES;
    bigScrollView.bounces = YES;
    bigScrollView.showsHorizontalScrollIndicator = NO;
    bigScrollView.showsVerticalScrollIndicator = NO;
    
    CGFloat scrollViewX = 0;
    CGFloat scrollViewY = NavigationHeigth;
    CGFloat scrollViewW = ScreenWidth;
    CGFloat scrollViewH = ScreenHeight - NavigationHeigth - NavigationHeigth;
    bigScrollView.frame = CGRectMake(scrollViewX, scrollViewY, scrollViewW, scrollViewH);
    [self addSubview:bigScrollView];
    self.bigScrollView = bigScrollView;
}

-(void)show{
    if (self.bigScrollView.subviews.count == 0) {
        //添加photoBrowser
        [JLKeyWindow addSubview:self];

        // 创建保存图片按钮
        [self showSaveImageButton];
    }
    
    // 创建当前页及总页显示
    [self.currentAndPageCountLabel removeFromSuperview];
    [self showNowPageAndPageCount:self.currentIndex pageCount:self.photos.count];
    // 获取原始frame
    [self setupOriginRects];
    
    // 设置滚动距离
    self.bigScrollView.contentSize = CGSizeMake(ScreenWidth*self.photos.count, 0);
    self.bigScrollView.contentOffset = CGPointMake(ScreenWidth*self.currentIndex, 0);
    
    // 创建子视图
    [self setupSmallScrollViews];
}


#pragma mark - 创建当前页及总页显示
- (void)showNowPageAndPageCount:(int)currentIndex pageCount:(NSInteger)pageCount {
    self.currentAndPageCountLabel = [[UILabel alloc] init];
    int nowCurrentIndex = currentIndex +1;
    if (nowCurrentIndex <10 && pageCount <10) {
        self.currentAndPageCountLabel.text = [NSString stringWithFormat:@"0%@/0%@", @(nowCurrentIndex), @(pageCount)];
    } else if (nowCurrentIndex >=10 && pageCount <10) {
        self.currentAndPageCountLabel.text = [NSString stringWithFormat:@"%@/0%@", @(nowCurrentIndex), @(pageCount)];
    } else if (nowCurrentIndex <10 && pageCount >= 10) {
        self.currentAndPageCountLabel.text = [NSString stringWithFormat:@"0%@/%@", @(nowCurrentIndex), @(pageCount)];
    } else {
        self.currentAndPageCountLabel.text = [NSString stringWithFormat:@"%@/%@", @(nowCurrentIndex), @(pageCount)];
    }
    [self.blackView addSubview:self.currentAndPageCountLabel];
    
    // 同label不同字体大小
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:self.currentAndPageCountLabel.text];
    NSRange range = [self.currentAndPageCountLabel.text rangeOfString:@"/"];
    NSDictionary *rangBeforedic = @{NSFontAttributeName:[UIFont systemFontOfSize:14]};
    NSDictionary *rangAfterdic = @{NSFontAttributeName:[UIFont systemFontOfSize:14]};
    [attrString addAttributes:rangBeforedic range:NSMakeRange(0, range.location)];
    [attrString addAttributes:rangAfterdic range:NSMakeRange(range.location, self.currentAndPageCountLabel.text.length - range.location)];
    [self.currentAndPageCountLabel setAttributedText:attrString];
    
    // 设置页码颜色以及布局
    [self setCountLabelColor];
}

/**
 设置页码颜色以及布局
 */
- (void)setCountLabelColor {
    self.currentAndPageCountLabel.textColor = [UIColor whiteColor];
    [self.currentAndPageCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.bottom.mas_equalTo(-15);
        make.height.mas_equalTo(30);
    }];
}


#pragma mark - 创建保存图片按钮
- (void)showSaveImageButton {
    UIButton *saveImageButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [saveImageButton setTitle:@"保存图片" forState:UIControlStateNormal];
    saveImageButton.titleLabel.font = ICONFONT(14);
    [saveImageButton addTarget:self action:@selector(progressSaveImageButton) forControlEvents:UIControlEventTouchUpInside];
    [self.blackView addSubview:saveImageButton];
    [saveImageButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.bottom.mas_equalTo(-15);
        make.height.mas_equalTo(30);
    }];
}


#pragma mark 创建子视图

-(void)setupSmallScrollViews{
    
    __weak JLPhotoBrowser *weakSelf = self;
    int firstIndex = (int)self.bigScrollView.subviews.count;
    for (int i=firstIndex; i<self.photos.count; i++) {
        
        UIScrollView *smallScrollView = [self creatSmallScrollView:i];
        JLPhoto *photo = [self addTapWithTag:i];
        [smallScrollView addSubview:photo];
        
        JLPieProgressView *loop = [self creatLoopWithTag:i];
        [smallScrollView addSubview:loop]; 
        
        
        NSURL *bigImgUrl = [NSURL URLWithString:photo.bigImgUrl];
        
        //检查图片是否已经缓存过
        [[SDImageCache sharedImageCache] queryCacheOperationForKey:photo.bigImgUrl done:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
            if (image==nil) {
                loop.hidden = NO;
            }
        }];
        
        
        [photo sd_setImageWithURL:bigImgUrl placeholderImage:nil options:SDWebImageRetryFailed | SDWebImageLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            //设置进度条
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                loop.progressValue = (CGFloat)receivedSize/(CGFloat)expectedSize;
            }];
            
        } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            if (image!=nil) {
                
                loop.hidden = YES;
                
                //下载回来的图片
                if (cacheType==SDImageCacheTypeNone) {
                    
                    [weakSelf setupPhotoFrame:photo];
                    
                }else{
                    
                    photo.frame = [weakSelf.originRects[i] CGRectValue];
                    [UIView animateWithDuration:0.3 animations:^{
                        [weakSelf setupPhotoFrame:photo];
                    }];
                    
                }
                
            }else{
                
                //图片下载失败
                photo.bounds = CGRectMake(0, 0, 240, 240);
                //                photo.center = CGPointMake(ScreenWidth/2, ScreenHeight/2);
                photo.center = CGPointMake(ScreenWidth /2, CGRectGetHeight(self.blackView.bounds) /3);
                photo.contentMode = UIViewContentModeScaleAspectFit;
                photo.image = [UIImage imageNamed:@"preview_image_failure"];
                
                [loop removeFromSuperview];
                
            }
        }];
    }
}

- (void)setupPhotoFrame:(JLPhoto *)photo{
    
    self.blackView.alpha = 1.0;
    
    photo.frame = photo.superview.bounds;
    
}

- (UIScrollView *)creatSmallScrollView:(int)tag{
    
    UIScrollView *smallScrollView = [[UIScrollView alloc] init];
    smallScrollView.backgroundColor = [UIColor clearColor];
    smallScrollView.tag = tag;
    
    smallScrollView.frame = CGRectMake(ScreenWidth*tag, 0, ScreenWidth, self.bigScrollView.height);
    smallScrollView.delegate = self;
    smallScrollView.maximumZoomScale=15.0;
    smallScrollView.minimumZoomScale=1;
    [self.bigScrollView addSubview:smallScrollView];
    return smallScrollView;
    
}

- (JLPhoto *)addTapWithTag:(int)tag{
    
    JLPhoto *photo = self.photos[tag];
    UITapGestureRecognizer *photoTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoTap:)];
    UITapGestureRecognizer *zonmTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(zonmTap:)];
    zonmTap.numberOfTapsRequired = 2;
    [photo addGestureRecognizer:zonmTap];
    [photo addGestureRecognizer:photoTap];
    
    //zonmTap失败了再执行photoTap，否则zonmTap永远不会被执行
    [photoTap requireGestureRecognizerToFail:zonmTap];
    
    return photo;
    
}

- (JLPieProgressView *)creatLoopWithTag:(int)tag{
    
    JLPieProgressView *loop = [[JLPieProgressView alloc] init];
    loop.tag = tag;
    loop.frame = CGRectMake(0,0 , 80, 80);
    loop.center = CGPointMake(ScreenWidth/2, ScreenHeight/2);
    loop.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
    loop.hidden = YES;
    UITapGestureRecognizer *loopTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(loopTap:)];
    [loop addGestureRecognizer:loopTap];
    return loop;
    
}

-(void)zonmTap:(UITapGestureRecognizer *)zonmTap{
    
    [UIView animateWithDuration:0.3 animations:^{
        
        UIScrollView *smallScrollView = (UIScrollView *)zonmTap.view.superview;
        smallScrollView.zoomScale = 3.0;
        
    }];
    
}

-(void)photoTap:(UITapGestureRecognizer *)photoTap{
    
    //1.将图片缩放回一倍，然后再缩放回原来的frame，否则由于屏幕太小动画直接从3倍缩回去，看不完整
    JLPhoto *photo = (JLPhoto *)photoTap.view;
    UIScrollView *smallScrollView = (UIScrollView *)photo.superview;
    smallScrollView.zoomScale = 1.0;
    
    //1.1如果是长图片先将其移动到CGPointMake(0, 0)在缩放回去 
    if (CGRectGetHeight(photo.frame)>ScreenHeight) {
        smallScrollView.contentOffset = CGPointMake(0, 0);
    }
    
    //2.再取出原始frame，缩放回去
    CGRect frame = [self.originRects[photo.tag] CGRectValue];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        photo.frame = frame;
        self.blackView.alpha = 0;
        if (self.JLPhotoBlock) {
            self.JLPhotoBlock(self.currentIndex);
        }
    }completion:^(BOOL finished) {
        
        [self removeFromSuperview];
        [self willRemoveSubview:self];
    }];
    
}

-(void)loopTap:(UITapGestureRecognizer *)tap{
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.blackView.alpha = 0;
        tap.view.alpha = 0;
        
    }completion:^(BOOL finished) {
        
        [self removeFromSuperview];
        
    }];
    
}

/** 保存到相册 */
- (void)progressSaveImageButton {
    [self.photos enumerateObjectsUsingBlock:^(JLPhoto *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == self.currentIndex) {
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                // 写入图片到相册
                PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:obj.image];
                NSLog(@"%@", req);
            } completionHandler:^(BOOL success, NSError * _Nullable error) {
                NSLog(@"success = %d, error = %@", success, error);
                if (success == YES) {
                    jxt_showAlertMessage(@"保存成功！");
                } else {
                    jxt_showAlertMessage(@"保存失败！");
                }
            }];
        }
    }];
}

#pragma mark 获取原始frame

-(void)setupOriginRects{
    
    [self.originRects removeAllObjects];
    
    for (JLPhoto *photo in self.photos) {
        
        UIImageView *sourceImageView = photo.sourceImageView;
        CGRect sourceF = [JLKeyWindow convertRect:sourceImageView.frame fromView:sourceImageView.superview];
        [self.originRects addObject:[NSValue valueWithCGRect:sourceF]];
        
    }
    
}

#pragma mark UIScrollViewDelegate

//告诉scrollview要缩放的是哪个子控件
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    
    if (scrollView.tag==bigScrollVIewTag) return nil;
    
    JLPhoto *photo = self.photos[scrollView.tag];
    
    return photo;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView{
    
    if (scrollView.tag==bigScrollVIewTag) return;
    
    JLPhoto *photo = (JLPhoto *)self.photos[scrollView.tag];
    
    CGFloat photoY = (ScreenHeight-photo.frame.size.height)/4;
    CGRect photoF = photo.frame;
    
    if (photoY>0) {
        
        photoF.origin.y = photoY;
        
    }else{
        
        photoF.origin.y = 0;
        
    }
    
    photo.frame = photoF;
    
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{
    
    //如果结束缩放后scale为1时，跟原来的宽高会有些轻微的出入，导致无法滑动，需要将其调整为原来的宽度
    if (scale == 1.0) {
        
        CGSize tempSize = scrollView.contentSize;
        tempSize.width = ScreenWidth;
        scrollView.contentSize = tempSize;
        CGRect tempF = view.frame;
        tempF.origin = CGPointZero;
        tempF.size.width = ScreenWidth;
        view.frame = tempF;
        
    }
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    int currentIndex = scrollView.contentOffset.x/ScreenWidth;
    
    if (self.currentIndex!=currentIndex && scrollView.tag==bigScrollVIewTag) {
        
        self.currentIndex = currentIndex;
        
        for (UIView *view in scrollView.subviews) {
            
            if ([view isKindOfClass:[UIScrollView class]]) {
                
                UIScrollView *scrollView = (UIScrollView *)view;
                scrollView.zoomScale = 1.0;
            }
            
        }
        
    }
    // 创建当前页及总页显示
    [self.currentAndPageCountLabel removeFromSuperview];
    [self showNowPageAndPageCount:self.currentIndex pageCount:self.photos.count];
    
    if (self.currentIndex == self.photos.count - 1) { // 已经滚到最后一张
        if (self.JLPhotoEndPageBlock) {
            self.JLPhotoEndPageBlock();
        }
    }
}

#pragma mark 设置frame

-(void)setFrame:(CGRect)frame{
    
    frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    
    [super setFrame:frame];
    
}


@end
